import { defineStore } from 'pinia'
import { loginApi, getUserInfo } from '@/api/auth/user'
import type { User } from '@/types/User'
import type { ApiResponse } from '@/api/types'
import { useAuthStore } from './auth'
const tempUser: User = {
  id: 0,
  username: '',
  email: '',
  role: 'USER',
  account_balance: 0,
  status: 'ACTIVE',
  created_at: new Date().toISOString(),
  updated_at: new Date().toISOString()
}
export const useUserStore = defineStore('user', {
  state: () => ({
    user: { ...tempUser },
    token: '', // 登录令牌
    loading: false // 用户信息加载状态
  }),
  persist: {
    key: 'sunlake-user-store',
    storage: window.localStorage,
    paths: ['user', 'token']
  } as any,
  actions: {
    setUsername(username: string) {
      this.user.username = username
    },
    setEmail(email: string) {
      this.user.email = email
    },
    setUser() {
      this.loading = true
      this.user = { ...tempUser }
    },
    setId(id: number) {
      this.user.id = id
    },
    getRole() {
      return this.user.role
    },
    clearUser() {
      this.user = { ...tempUser }
      this.loading = false
      this.token = ''
    },
    setToken(token: string) {
      this.token = token
    },
    async login(payload: { email: string; password: string }) {
      const res: ApiResponse<any> = await loginApi(payload)
      if (res.code === 0 || res.code === 200) {
        console.log('登录成功')
        this.setToken(res.accessToken || '')
        this.loading = true
        await this.fetchUserInfo()
        return true
      }
      else
      {
        throw new Error(res.message || '登录失败')
      }
    },
    async fetchUserInfo() {
      console.log('token', this.token)
      if (!this.token) {
        console.warn('无效的 token，无法获取用户信息')
        return
      }
      const res: ApiResponse<User> = await getUserInfo({ token: this.token })
      console.log('fetchUserInfo response:', res)
      if (res.code === 0 || res.code === 200) {
        Object.assign(this.user, res.data)
        const authStore = useAuthStore()
        authStore.setTokens(res.accessToken || null, (res.data as any)?.refreshToken || null)
        console.log('用户信息获取成功:', this.user)
      } else {
        throw new Error(res.message || '获取用户信息失败')
      }
    },
    async logout() {
      this.clearUser()
      const authStore = useAuthStore()
      authStore.setTokens(null, null)
    },

  },
  getters: {
    isLoggedIn: (state) => !!state.user && !!state.token,
    isAdmin: (state) => state.user?.role === 'ADMIN'
  }
})